package org.huangrui.javase.api;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @Author hr
 * @Create 2025-11-07 11:42
 **/
public class T03StringTransferCoder {
    public static void main(String[] args) throws IOException {
        test1();
        test2();
    }

    private static void test2() throws IOException {
        Charset utf8 = Charset.forName("UTF-8");
        Charset gbk = Charset.forName("GBK");
        FileReader fr = new FileReader("d:\\UTF8.txt",utf8);
        FileWriter fw = new FileWriter("d:\\GBK.txt", gbk);
        char[] data = new char[10];
        int len;
        while((len=fr.read(data))!=-1){
            fw.write(data,0,len);
        }
        fw.close();
        fr.close();
    }

    private static void test1() {
        Charset utf8Charset = StandardCharsets.UTF_8;
        Charset gbkCharset = Charset.forName("GBK");

        //originalBytes的内容可能是从文件中读取，或从网络中接收，这里临时模拟一下
        //总之，读取的是以UTF-8编码规则处理的数据
        String str ="尚硅谷";
        byte[] originalBytes = str.getBytes(utf8Charset);
        byte[] destBytes = change(originalBytes, utf8Charset, gbkCharset);

        System.out.println("Bytes in UTF-8: " + Arrays.toString(originalBytes));
        System.out.println("Bytes in GBK：" + Arrays.toString(destBytes));
        System.out.println("UTF-8的字符串内容：" + new String(originalBytes,utf8Charset));
        System.out.println("GBK的字符串：" + new String(destBytes,gbkCharset));
    }

    public static byte[] change(byte[] originalBytes, Charset originalCharset, Charset destCharset){
        String temp = new String(originalBytes,originalCharset);
        byte[] destBytes = temp.getBytes(destCharset);
        return destBytes;
    }
}
